/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.fixlength;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author 卢清波
 * @date 2021/2/3 15:59
 */
public class FixLengthDecode extends ByteToMessageDecoder
{

    private int length ;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception
    {

        if(in.readableBytes() >= 4)
        {
            if(length==0)
            {
                length = in.readInt();
            }
            if(in.readableBytes()<length)
            {
                System.out.println("还没有接收完数据，请继续等待！");
                return;
            }
            // 解决拆包，粘包的关键，bytebuf缓冲区读取固定长度的数据
            if(in.readableBytes()>=length)
            {
                byte[] content = new byte[length];
                in.readBytes(content);
                MyMessage myMessage = new MyMessage();
                myMessage.setLength(length);
                myMessage.setContent(content);
                out.add(myMessage);
            }
            length = 0 ;
        }

    }
}
